var util = require("../../libs/util.js");
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromWhDistance: 0,
    canCheckin: false,
    canDock: false,
    canLeave: false,
    ischeckin: false,
    checkin_need_distance: 30000,
    booking_plate_btn_text: '没有开放的仓库',
    checkinData: [],
    lpListData: [],
    lpQueue: {},
    beforeQueueNumber:0,
    lpdata:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    var that = this;
    that.setData({
      CustomBar: app.globalData.CustomBar,
      vehicle: app.globalData.vehicleId,
      driver: app.globalData.driverId,
      plate: app.globalData.plate
    });
    if(e.id){
      that.setData({
        lpId:e.id
      })
      //获取预约数据
      that.getDataList(e.id);
    }else{
      //获取预约数据
      that.getDataList();
    }
  },
  refresh: function() {
    this.getDataList();
  },
  changeLP:function(){
    var that = this;
    var lp_delivery_data = that.data.lp_delivery_data;
    var itemList = [];
    for(var i=0;i<lp_delivery_data.length;i++){
       if(i<6){
        itemList.push(lp_delivery_data[i].warehouse)
       }
    }
    wx.showActionSheet({
      itemList: itemList,
      success (res) {
        console.log(res.tapIndex)
        that.getDataList(lp_delivery_data[res.tapIndex].ID);
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
  getDataList: function(lpid) {
    wx.showLoading({
      title: '加载数据中...'
    });
    var that = this;
    that.setData({
      canCheckin: false,
      canDock: false,
      canLeave: false,
      ischeckin: false,
      booking_plate_btn_text: '没有开放的仓库'
    })
    var lp_default;
    //记录默认卡口
    try {
      var lp_default = wx.getStorageSync('lp_default')
    } catch (e) {}
    util.getData("/atapi/loadingplatform/loadingplatform/lpByDriver", {
      lpid:lpid||lp_default||'',
      CO_ID: app.globalData.CO_ID,
      user_id: app.globalData.user_id,
      plate: app.globalData.plate,
      vehicle: app.globalData.vehicleId
    }, function(res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (res.data.success) {
        var data = res.data.data;
        that.setData(data);
        that.setData({
          lp_delivery_data:res.data.lp_delivery_data
        })
        //设置默认卡口
        try {
          wx.setStorageSync('lp_default', that.data.lpId)
        } catch (e) { }
        // var dcQueueData = that.data.dcQueueData;
        // if (dcQueueData.queueTime == 0) {
        //   that.setData({
        //     'dcQueueData.queueHour': 0,
        //     'dcQueueData.queueMinute': 0
        //   })
        // } else {
        //   var minute = dcQueueData.queueTime;
        //   that.setData({   
        //   })
        // }
        // var dcBookingData = that.data.dcBookingData;
        // //如果有签到
        //try{
        
        if (data.checkin) {
          that.setData({
            ischeckin: true
          });
          //如果已经列入队列
          if (data.checkin.lp_number) {
            console.log(1111111111)
            var lp_number = data.checkin.lp_number;
            var checkinData = data.checkinData;
            //前面排队人数
            var queueNumber = 0, beforeQueueNumber = 0, _beforeQueueNumber = 0;
            for (var i = 0; i < checkinData.length;i++){
              if (checkinData[i].lp_number == lp_number && checkinData[i].vehicle != app.globalData.vehicleId){
                queueNumber++;
              }
              if (checkinData[i].lp_number == lp_number) {
                _beforeQueueNumber += 1;
              }
              if (checkinData[i].vehicle == app.globalData.vehicleId) {
                beforeQueueNumber = _beforeQueueNumber - 1;
              }
            }
            if (beforeQueueNumber < 0){
              beforeQueueNumber = 0;
            }
            var working_time = that.data.lpListData[lp_number - 1].working_time || 40;
            console.log(working_time)
            var wait_minute = queueNumber * Number(working_time),wait_hour = 0;
            if (wait_minute < 60){
              wait_hour = 0;
            }else{
              wait_hour = Math.floor(wait_minute/60);
              wait_minute = wait_minute%60
            }
            if (wait_minute > 0) {
              that.setData({
                'dcQueueData.queueHour': wait_hour,
                'dcQueueData.queueMinute': wait_minute
              })
            }
            that.setData({
              beforeQueueNumber: beforeQueueNumber,
              lpQueue: {
                lp_number: lp_number,
                plate: that.data.lpListData[lp_number - 1].plate,
                in_time: that.data.lpListData[lp_number - 1].in_time,
                out_time: that.data.lpListData[lp_number - 1].out_time
              }
            });
            if (data.checkin.is_load == 1) {
              that.setData({
                canCheckin: false,
                booking_plate_btn_text: '已完成'
              })
            } else {
              //console.log(data.lpListData[data.checkin.lp_number - 1].vehicle == app.globalData.vehicleId)
              //console.log(!data.lpListData[data.checkin.lp_number - 1].in_time == true)
              //装卸中
              if (data.lpListData[lp_number - 1].vehicle == app.globalData.vehicleId && data.lpListData[lp_number - 1].in_time && data.checkin.is_load == 0) {
                that.setData({
                  canCheckin: true,
                  canLeave: true,
                  booking_plate_btn_text: '装卸中，已完成请点击确认'
                })
              } else if (data.lpListData[lp_number - 1].vehicle == app.globalData.vehicleId && !data.lpListData[lp_number - 1].in_time) {
                that.setData({
                  canCheckin: true,
                  canDock: true,
                  booking_plate_btn_text: '请靠台，已靠台请点击确认'
                })
              } else {
                that.setData({
                  canCheckin: false,
                  booking_plate_btn_text: '排队中'
                })
              }
            }
          } else {
            that.setData({
              canCheckin: false,
              booking_plate_btn_text: '等待排队'
            })
          }
        } else {
          that.setData({
            canCheckin: true,
            booking_plate_btn_text: '装卸货预约'
          })
        }
        //}catch(e){}
        //计算距离仓库距离
        that.getFromDcDistance();
      } else {
        that.setData({
          hasData: false
        })
      }
    });
  },
  getFromDcDistance: function() {
    var that = this;
    var coord = String(that.data.coord).split(",");
    //获取手机定位坐标
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        console.log(res)
        var latitude = res.latitude;
        var longitude = res.longitude;
        util.getData("/xypapi/map/routerCalculate/getDrivingPathOfCoord", {
          lat: latitude,
          lon: longitude,
          nextLat: coord[0],
          nextLon: coord[1]
        }, function(res, error) {
          console.log(res)
          if (res.data.success) {
            var canCheckin = true;
            if (Number(res.data.data.distance) > Number(that.data.checkin_need_distance) && Number(that.data.checkin_need_distance) > 0) {
              if (that.data.ischeckin == false) {
                that.setData({
                  canCheckin: false,
                  booking_plate_btn_text: '距离超过' + that.data.checkin_need_distance + '米，不能签到'
                });
              }
            }
            if (Number(that.data.checkin_need_distance) == 0) {}
            that.setData({
              fromWhDistance: Number(res.data.data.distance / 1000).toFixed(2),
              canCheckin: that.data.canCheckin == false ? false : canCheckin //优先预约的状态
            })
          }
        });
      }
    });
  },
  showDcLocation: function() {
    var coord = String(this.data.coord).split(",");
    wx.openLocation({
      latitude: parseFloat(coord[0]),
      longitude: parseFloat(coord[1]),
      scale: 28
    })
  },
  gotoBooking: function() {
    var that = this;
    if (!that.data.canCheckin) {
      return false;
    }
    //靠台
    if (that.data.canDock) {
      wx.showLoading({
        title: '提交中...'
      });
      util.postData("/atapi/loadingplatform/loadingplatform/dockToPlat", {
        CO_ID: that.data.CO_ID,
        lp: that.data.lpId,
        lp_number: that.data.checkin.lp_number
      }, function (res, error) {
        wx.hideLoading();
        console.log(res);
        console.log(error)
        if (res.data.success) {
          //app.socket.emit('lp', { to_user: that.data.manager,type: 'dock', lp: that.data.lpId,lp_number: that.data.checkin.lp_number,name: app.globalData.truename, user_id: app.globalData.user_id, plate: app.globalData.plate, vehicle: app.globalData.vehicleId });
          wx.hideLoading();
          wx.showToast({
            title: res.data.data,
            icon: 'success',
            duration: 3000,
            mask: true,
            success: function() {
              //获取记录
              setTimeout(function() {
                that.getDataList();
              }, 3000)
            }
          })
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 2000
          })
        }
      });
      //离台
    } else if (that.data.canLeave) {
      wx.showLoading({
        title: '提交中...'
      });
      util.postData("/atapi/loadingplatform/loadingplatform/leavePlat", {
        CO_ID: that.data.CO_ID,
        lp: that.data.lpId,
        lp_number: that.data.checkin.lp_number,
        checkinId: that.data.checkin.ID
      }, function(res, error) {
        console.log(res);
        console.log(error)
        wx.hideLoading();
        if (res.data.success) {
          //app.socket.emit('lp', { to_user: that.data.manager, type: 'leave', lp: that.data.lpId, lp_number: that.data.checkin.lp_number, name: app.globalData.truename, user_id: app.globalData.user_id, plate: app.globalData.plate, vehicle: app.globalData.vehicleId });
          wx.showToast({
            title: res.data.data,
            icon: 'success',
            duration: 3000,
            mask: true,
            success: function() {
              //获取记录
              setTimeout(function() {
                that.getDataList();
              }, 3000)
            }
          })
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 2000
          })
        }
      });
    } else {
      wx.showLoading({
        title: '签到中...'
      });
      util.postData("/atapi/loadingplatform/loadingplatform/checkin", {
        CO_ID: that.data.CO_ID,
        lp: that.data.lpId,
        plate: app.globalData.plate,
        vehicle: app.globalData.vehicleId,
        delivery: that.data.delivery,
        path_name: that.data.path_name,
        autoQueue: that.data.autoQueue
      }, function(res, error) {
        console.log(res);
        console.log(error)
        wx.hideLoading();
        if (res.data.success) {
          //app.socket.emit('lp', { to_user: that.data.manager,type: 'checkin', lp: that.data.lpId, name: app.globalData.truename, user_id: app.globalData.user_id, plate: app.globalData.plate, vehicle: app.globalData.vehicleId });
          wx.showToast({
            title: res.data.data,
            icon: 'success',
            duration: 2000,
            mask: true,
            success: function() {
              //获取记录
              setTimeout(function() {
                that.getDataList();
              }, 2000)
            }
          })
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 2000
          })
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})